#!usr/bin/env node

const Koa = require('koa'),
      koaBody = require('koa-body'),
      Router = require('koa-router'),
      path = require('path'),
      fs = require('fs');

const app = new Koa(),
      router = new Router();
    
app.use(koaBody({
  multipart:true,
  formidable:{
    keepExtensions:true,
    maxFileSize:1000*1024*1024,
    uploadDir:path.join(__dirname,'upload')
  }
}))

const savePath = path.join(__dirname,'upload')
if(!fs.existsSync(savePath)){
  fs.mkdirSync(savePath)
}

app.use(router.routes());

router.get('/',async (ctx)=>{
  ctx.set('Content-Type','text/html');
  ctx.type='html';
  const pathUrl = path.join(__dirname,'upload.html')
  ctx.body = fs.createReadStream(pathUrl);
})

router.post('/upload',async (ctx)=>{
  const file = ctx.request.files.file;
 
  const filePath = path.join(__dirname,'/upload')+`/${file.name}`;

  ctx.body = fs.readFileSync(file.path);
  ctx.set('Content-Type','text/json');
  console.log('上传成功')
})

app.listen(8080);
